
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Product {

   Product({this.name});
   String? name;
}

typedef CartChangedCallback = void Function(Product product, bool inCart);


class ShoppingListItem extends StatelessWidget {
  ShoppingListItem({Product? product, this.inCart, this.onCartChanged})
      : product = product,

        super(key: ObjectKey(product));

  final Product? product;
  final bool? inCart;
  final CartChangedCallback? onCartChanged;

  Color _getColor(BuildContext context) {
    // The theme depends on the BuildContext because different parts of the tree
    // can have different themes.  The BuildContext indicates where the build is
    // taking place and therefore which theme to use.

    return (inCart ==null || inCart!)? Colors.green : Colors.blue;
  }

  TextStyle? _getTextStyle(BuildContext context) {
    if (inCart ==null || !inCart!) return null;

      print("文字改变状态");
    return const TextStyle(
      color: Colors.red,
      decoration: TextDecoration.lineThrough,
    );
  }

  @override
  Widget build(BuildContext context) {
    return  ListTile(
      onTap: () {
          onCartChanged!(product!, !inCart!);
      },
      leading: CircleAvatar(
        backgroundColor: _getColor(context),
        child: Text(product!.name![0]),
      ),
      title: Text(product!.name!, style: _getTextStyle(context)),
    );
  }
}

class ShoppingList extends StatefulWidget{

  late final List<Product>? products;
  ShoppingList({Key? key, this.products}) : super(key: key);

  @override
  _ShoppingListState createState() => _ShoppingListState();
}

class _ShoppingListState extends State<ShoppingList> {
  final Set<Product> _shoppingCart = <Product>{};

  void _handleCartChanged(Product product, bool inCart) {
    setState(() {
      // When user changes what is in the cart, we need to change _shoppingCart
      // inside a setState call to trigger a rebuild. The framework then calls
      // build, below, which updates the visual appearance of the app.

      if (inCart) {
        _shoppingCart.add(product);
      } else {
        _shoppingCart.remove(product);
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar:  AppBar(
        title:  const Text('Shopping List'),
      ),
      body:  ListView(
        padding:  const EdgeInsets.symmetric(vertical: 8.0),
        children: widget.products!.map((Product product) {
          return  ShoppingListItem(
            product: product,
            inCart: _shoppingCart.contains(product),
            onCartChanged: _handleCartChanged,
          );
        }).toList(),
      ),
    );
  }
}






